package com.lance.answer.question_answer.xj_new;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.dto.Item;
import com.lance.answer.dto.XjCourseVideoInfo;
import com.lance.answer.gui.answer.Question;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.question_answer.XjCourseInfo;
import com.lance.answer.util.HttpUtil;
import com.lance.answer.util.XinJiangUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.Duration;
import java.util.*;

/**
 * 获取作业的视频信息 能用的1027|1120 获取每门课程的视频信息
 */
public class GetGkQuestionVideoByTeacher {



    public static List<WebElement> findElementsByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<List<WebElement>>)
                d -> d.findElements(By.cssSelector(cssSelector))));
    }

    public static WebElement findElementByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<WebElement>)
                d -> d.findElement(By.cssSelector(cssSelector))));
    }

    public static void main(String[] args) throws Exception {

        WebDriver driver = Util.getDriver(null);
        String url = "https://xjskk.open.com.cn/teacherspace-auth/#/login";
        // 打开指定的网站
        driver.get(url);
        Thread.sleep(200);
     //   String courseId = "30944";  //职业生涯规划（1）

        for (WebElement we : driver.findElements(By.className("el-input__inner"))) {
            if ("text".equals(we.getAttribute("type"))) {
                we.sendKeys(new String[]{"lijunj"});
            }
            if ("password".equals(we.getAttribute("type"))) {
                we.sendKeys(new String[]{"lijunj"});
            }
        }
        driver.findElement(By.cssSelector("button[class='el-button login-ruleForm-btn el-button--primary']")).click();

        // 进入课程观察员角色的页面

        findElementByCssSelector(driver, "div[title='课程观察员']", 20).click();

        Thread.sleep(5000);





        List<String> ids = Lists.newArrayList();
        for(File f1:new File("D:\\新疆一体化2\\CourseInfoDeal").listFiles()){
            String fileName = f1.getName();
            String name = fileName.substring(0,fileName.length()-5);
            System.err.println("name:"+name);
            ids.add(name);
        }



        InputStream inputStream = new FileInputStream("E:\\排名map.txt");
        List<String> allKeyValues = IOUtils.readLines(inputStream, "utf-8");

        Map<String,String> mapTmp = Maps.newHashMap();
        for(String keyValues:allKeyValues){
            String[] strs = keyValues.split("&");
            String k1 = strs[0];
            String v1 = strs[1];
         //   mapTmp.put(k1,v1);
            mapTmp.put(k1,v1);
        }


        for(File file:new File("E:\\XjStudentCourseInfoTmp\\names").listFiles()){
            if(file.isDirectory()){
                continue;
            }
            String fileName = file.getName();
            String code =  fileName.substring(0,fileName.length()-5);
            System.err.println("code::::::::"+code);
            if(ids.contains(code)){
              continue;
            }
            try {

                System.err.println("code:"+code);
                System.err.println("mapTmp.get(code):"+mapTmp.get(code));
                String courseId = code;
                String subjectName = mapTmp.get(code);

                if("管理信息系统".equals(subjectName)){
                    continue;
                }
                if("C语言程序设计".equals(subjectName)){
                    continue;
                }
                // fixme 2022-4-12 实际中是要删掉的....................
//                if(!"婚姻家庭法学".equals(subjectName)){
//                    continue;
//                }
                /**
                 * 38510&人才测评技术及应用
                 * 38557&劳务派遣讲座
                 * 38539&劳动争议与仲裁讲座
                 */
                if(
//                        !"企业文化".equals(subjectName)
  //                              !"人才测评技术及应用".equals(subjectName)
    //                            !"劳务派遣讲座".equals(subjectName)
                                !"现代教师学导论".equals(subjectName)
                          //              &&!"文艺理论基础".equals(subjectName)
                                        &&!"小学儿童教育心理学".equals(subjectName)
                                        &&!"心理学".equals(subjectName)
                                        &&!"阅读与写作(2)".equals(subjectName)
                ){
                    continue;
                }
                // fixme 2022-4-12 实际中是要删掉的....................
                System.out.println("-----------------------------------------------------------");


                //  int courseId =  itemsDTO.getOpenCourseId();
                // FIXME 进入某门课程
                driver.get("https://xjskk.open.com.cn/teacher/#/menu/mission?openCourseId="+courseId);
                Thread.sleep(3000);
                Set<Cookie> cookies = driver.manage().getCookies();
                String studentSpaceProfile = Util.getStudentSpaceProfile(cookies);
                String authorization = Util.getAuthorization(cookies);
                // 初始化头部
                Map<String, String> heads = XinJiangUtil.initHttpHeads(studentSpaceProfile, authorization);

                String cookie = Util.getCookie(cookies);

                String getUrl = "https://xjskk.open.com.cn/api/teacher/teacher-space-service/taskCatalogs?openCourseId="+courseId;

                String courseInfoJson = HttpUtil.get(getUrl,cookie,heads);

                System.err.println("courseInfoJson:"+courseInfoJson);

                XjCourseVideoInfo videoInfo = JSON.parseObject(courseInfoJson,XjCourseVideoInfo.class);
                // 原始的
                FileUtils.write(new File("D:\\新疆一体化2\\CourseInfoOrigin\\"  + courseId+".json"), JSONObject.toJSONString(videoInfo, SerializerFeature.PrettyFormat), "utf-8");

                List<XjCourseVideoInfo.ContentDTO> dtoList = Lists.newLinkedList();
                for(XjCourseVideoInfo.ContentDTO contentDTO:videoInfo.getContent()){
                    if(contentDTO.getExamines().size()==0&&contentDTO.getResources().size()==0){
                        continue;
                    }
                    dtoList.add(contentDTO);
                }
                videoInfo.setContent(dtoList);

                // 处理后的
                FileUtils.write(new File("D:\\新疆一体化2\\CourseInfo\\"  + courseId+".json"), JSONObject.toJSONString(videoInfo, SerializerFeature.PrettyFormat), "utf-8");
                Thread.sleep(1000);

                // https://xjskk.open.com.cn/teacher/#/play?openCourseId=33336&type=1&resourceId=066fd669-2443-470e-92d6-42463ee01ff6&link=VEadntqDATA20210407163241857.mp4&extensionName=.mp4&from=menu&treeType=2
                //    https://xjskk.open.com.cn/teacher/#/play?extensionName=.mp4&&treeType=2&link=VElrgljDATA20210328115835494.mp4&typ=1&from=menu&
                //  https://xjskk.open.com.cn/teacher/#/play?&type=1&&link=VElrgljDATA20210328115835494.mp4&extensionName=mp4&from=menu&treeType=1
                // 获取视频的长度信息
                /**
                 * 	"enable":0,
                 * 				"extendName":".mp4",
                 * 				"fileId":"VEadntqDATA20210407163241857.mp4",
                 * 				"kind":1,
                 * 				"name":"0金融市场导学.mp4",
                 * 				"resourceUid":"066fd669-2443-470e-92d6-42463ee01ff6",
                 * 				"type":1
                 */

                for(XjCourseVideoInfo.ContentDTO contentDTO:videoInfo.getContent()){
                    for(XjCourseVideoInfo.ContentDTO.ResourcesDTO resources:contentDTO.getResources()){
                        Map<String,Object> map = Maps.newHashMap();
                        map.put("openCourseId",courseId);
                        map.put("type",resources.getType());
                        map.put("resourceId",resources.getResourceUid());
                        map.put("link",resources.getFileId());
                        map.put("extensionName",resources.getExtendName());
                        map.put("from","menu");
                        map.put("treeType",2);
                        StringBuilder sb = new StringBuilder("https://xjskk.open.com.cn/teacher/#/play?");
                        for(Map.Entry<String,Object> entry:map.entrySet()){
                            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                        }
                        String getUrl2 = sb.toString();
                        getUrl2 = getUrl2.substring(0,getUrl2.length()-1);
                        System.err.println("getUrl2:"+getUrl2);
                        Thread.sleep(1000);
                        driver.get(getUrl2);
                        Thread.sleep(2000);
                        ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,100000)");
                        Thread.sleep(5000);
                        //  String timeString = driver.findElement(By.className("duration")).getText();
                        String timeString = findElementByCssSelector(driver,"*[class='duration']",30).getText();

                        int traceTime = getTime(timeString);

                        System.err.println("timeString:::::::::::"+timeString+"  traceTime:"+traceTime);
                        resources.setTraceTime(traceTime);
                        driver.navigate().back();
                        Thread.sleep(2000);
                    }

                }
                //    FileUtils.write(new File("D:\\新疆一体化2\\CourseInfoDeal\\"  + courseId+".json"), JSONObject.toJSONString(videoInfo, SerializerFeature.PrettyFormat), "utf-8");
                FileUtils.write(new File("D:\\新疆一体化2\\CourseInfoDeal\\"  + courseId+".json"), JSONObject.toJSONString(videoInfo, SerializerFeature.PrettyFormat), "utf-8");

                Thread.sleep(10000);
            }catch (Exception ee){

            }

        }




        // TODO https://xjskk.open.com.cn/api/teacher/teacher-space-service/courses?pageNumber=1&pageSize=20&status=0&semesterId=23
        Thread.sleep(5000);








    }
    /**
     * 将字符串的时间转成秒数
     * @param s 字符串时间 06：03
     * @return 秒数
     */
    public static int getTime(String s){
        int time = 0;
        try {
            String[] array = s.split(":");
            int i =array.length-1;
            for(String a:array){
                time += Math.pow(60,i)*Integer.parseInt(a);
                i--;
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return time;
    }

}
